package org.hbgl.geoentity.admin.web.unit;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hbgl.geoentity.admin.annotation.OperationLog;
import org.hbgl.geoentity.admin.annotation.RequiresPermissionsDesc;
import org.hbgl.geoentity.admin.aspect.OperationType;
import org.hbgl.geoentity.admin.shiro.UserType;
import org.hbgl.geoentity.admin.web.BaseController;
import org.hbgl.geoentity.core.util.JacksonUtil;
import org.hbgl.geoentity.core.util.RegexUtil;
import org.hbgl.geoentity.core.util.ResponseUtil;
import org.hbgl.geoentity.core.util.bcrypt.BCryptPasswordEncoder;
import org.hbgl.geoentity.db.domain.GeDepartment;
import org.hbgl.geoentity.db.domain.GeRole;
import org.hbgl.geoentity.db.domain.GeUnit;
import org.hbgl.geoentity.db.domain.GeUser;
import org.hbgl.geoentity.db.util.EnumFile;
import org.hbgl.geoentity.db.vo.UserVo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

import static org.hbgl.geoentity.admin.util.ResponseCode.*;

/**
 * 代码功能：账号管理
 * 开发日期：2022/4/26
 * 作者：蒋海仑
 * 联系方式：
 * 版本更迭说明：
 * 版权信息：河北广联信息技术有限公司
 */
@RestController
@RequestMapping("/unit/user")
@Validated
public class UnitUserController extends BaseController {

    /**
     * 重置密码
     *
     * @param body { id : 账号ID, password : 新密码 }
     */
    @OperationLog(detail = "重置密码", operationType = OperationType.UPDATE, userType = UserType.UNIT)
    @PostMapping("/password")
    public Object password(@RequestBody String body) {
        String password = JacksonUtil.parseString(body, "password");
        if (!ObjectUtils.allNotNull(
                password
        )) {
            return ResponseUtil.badArgument();
        }
        if (password.length() < 6) {
            return ResponseUtil.fail(ADMIN_INVALID_PASSWORD, "密码长度不能小于6");
        }

        GeUser userCurrent = getCurrentUnitUser();

        GeUnit userLatest = unitService.findById(userCurrent.getId());
        if (userLatest == null) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser user = new GeUser();
        user.setId(userCurrent.getId());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(password));

        if (userService.updateByIdSelective(user) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

}
